// axios 基础封装
import axios from "axios";
import {useUserStore} from '@/stores/userStore.js'
import router from "@/router";
import {ElMessage} from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'


const http = axios.create({
    baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
    timeout: 10000
});

// 拦截器
// axios请求拦截器
http.interceptors.request.use(config => {
    // token
    const userInfoStore = useUserStore()

    const token = userInfoStore.userInfo.token
    if (token) {
        config.headers.Authorization = `Bearer ${token}`
    }

    return config
}, e => Promise.reject(e))

// axios响应式拦截器
http.interceptors.response.use(res => res.data, e => {
    // 统一失败处理
    ElMessage({
        type: 'warning',
        message: e.response.data.message
    })
    // 401 token失效处理
    if (e.response.status === 401) {
        const userInfoStore = useUserStore()
        userInfoStore.clearUserInfo()
        // 跳转到登录页面
        router.push('/login')
    }
    return Promise.reject(e)
})

export default http;